/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.base;

import picounit.features.Feature;

import java.util.Set;

class ParsedFeatureDescription implements FeatureDescription {
	private final String className;
	private final FeatureInstantiator featureInstantiator;

	public ParsedFeatureDescription(String line, Prefixer prefixer, FeatureInstantiator featureInstantiator) {
		this.className = prefixer.prefix(line);
		this.featureInstantiator = featureInstantiator;
	}

	public void insertInto(FeatureRegistry featureRegistry, Set<String> featuresLoaded) {
		if (featuresLoaded.contains(className)) {
			return;
		}

		try {
			Class<?> featureClass = Class.forName(className);

			if (Feature.class.isAssignableFrom(featureClass)) {			
				Feature feature = featureInstantiator.instantiate(castToFeatureClass(featureClass));

//				System.out.println("Inserting feature: " + featureClass);
				feature.addFeatures(featureRegistry);

				featuresLoaded.add(className);
			}
		}
		catch (Exception exception) {
//			System.err.println("Unable to insert feature: " + className);
//			exception.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	private <F extends Feature> Class<F> castToFeatureClass(Class<?> featureClass) {
		return (Class<F>) featureClass;
	}
}